package com.aube.interact.taste.card;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aube.interact.taste.R;
import com.aube.interact.taste.controller.DataManager;
import com.aube.interact.taste.model.OptionResultModel;
import com.aube.interact.taste.model.ReportResultModel;
import com.aube.interact.taste.model.TimeLinePiece;
import com.aube.interact.taste.model.VoteData;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hill on 16/12/12.
 */

public class QAViewUp extends BaseCardNew implements View.OnClickListener {
    private final String TAG = "Aube/QAViewup";

    private List<QAOptionViewUp> mOptionList = new ArrayList<>();
    private VoteData mVoteData;

    private int mPreselectedIndex = -1;

    private ValueAnimator mProgressAnimator;

    public QAViewUp(Context context) {
        this(context, null);
    }
    public QAViewUp(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public QAViewUp(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    @Override
    public void init(final TimeLinePiece data, ChannelDetail detail) {
        super.init(data, detail);
        initView();
    }

    @Override
    protected void initView() {
        Utils.Log(TAG, "[initView] ");
        LayoutInflater.from(getContext()).inflate(R.layout.aube_intera_layout_sdk_qaup, this);

        mRoot = (FrameLayout) findViewById(R.id.sdk_qaup_root);
        mOptionGp = (LinearLayout) findViewById(R.id.sdk_qaup_optiongp);
        mFoldText = (TextView) findViewById(R.id.sdk_qaup_expand);
        mCloseView = findViewById(R.id.sdk_qaup_close);
        mDivisionView = findViewById(R.id.sdk_qaup_division_line);
        mTitleText = (TextView) findViewById(R.id.sdk_qaup_titletext);
        mParticipantsText = (TextView) findViewById(R.id.sdk_qaup_people);
        mBetterCloseView = findViewById(R.id.sdk_qaup_closeclickview);

        mTitleText.setText(mData.title);

        super.initView();

        fillOption();

        Utils.Log(Utils.LogType.DEBUG, TAG, "initView end");
    }

    private void fillOption() {
        mPreselectedIndex = DataManager.getInstance(mContext).getIndex(mData.rid);
        mCountdown = mData.getCountDownDuration();
        mOptionLineHeight = Utils.dip2px(mContext, 0.5f);
        mOptionViewHeight = Utils.dip2px(mContext, 40);

        if(mData == null || mData.optionSize() == 0) return;

        for(int i = 0; i < mData.optionSize(); i++) {
            QAOptionViewUp voteOption = new QAOptionViewUp(mContext);
            voteOption.initView(mData.getOptions().get(i));
            voteOption.setTag("QAOptionViewUp_" + i);
            voteOption.setOnClickListener(this);
            mOptionList.add(voteOption);
            mOptionGp.addView(voteOption);
        }

        mVoteData = new VoteData(mContext);
        mVoteData.compose(mData);

        updateView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if(mOptionGp.getVisibility() == View.VISIBLE) {
            if(!mBAnimating) {
                mOptionGpHeight = mOptionGp.getMeasuredHeight();
            }
            mRootHeight = mTitleText.getMeasuredHeight() + mOptionGpHeight + mParticipantsText.getMeasuredHeight() + mTasteStyleHeight;
        } else {
            mRootHeight = mTitleText.getMeasuredHeight() + mDivisionViewHeight + mParticipantsText.getMeasuredHeight() + mTasteStyleHeight;
        }

        if(mBAnimating) {
            mRootHeight = mAnimHeight;
        }

        measureChild(getChildAt(0), View.MeasureSpec.makeMeasureSpec(widthMeasureSpec, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(mRootHeight, View.MeasureSpec.EXACTLY));
        setMeasuredDimension(View.MeasureSpec.makeMeasureSpec(getMeasuredWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(mRootHeight, View.MeasureSpec.EXACTLY));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        mDivisionViewTop = mTitleText.getMeasuredHeight();
        mDivisionView.layout(BasicMargin, mDivisionViewTop, BasicMargin + mTitleText.getMeasuredWidth(), mDivisionViewTop + mDivisionViewHeight);

        mOptionGpTop =  mTitleText.getMeasuredHeight();
        mOptionGp.layout(BasicMargin, mOptionGpTop, BasicMargin + mOptionGp.getMeasuredWidth(), mOptionGpTop + mOptionGp.getMeasuredHeight());
    }

    @Override
    public void onClick(View v) {
        if(mVoteData.getQAAnswerReveal())
            return;

        for(int i = 0; i < mOptionList.size(); i++) {
            QAOptionViewUp optionViewEx = mOptionList.get(i);
            if(v.getTag().equals(optionViewEx.getTag())) {
                report(mVoteData.mRid, mVoteData.getReportOptionId(i), mVoteData.getReportCancelId(i), true);
                mVoteData.update(i);
            }
        }

        updateView();
    }

    private void updateView() {
        Utils.Log(TAG, "[updateView]");

        for(int i = 0; i < mOptionList.size(); i++) {
            int mOptionPercent = mVoteData.getOptionPercent(mData.getOptionIdByIndex(i));

            QAOptionViewUp optionViewUp = mOptionList.get(i);
            optionViewUp.mPercentText.setText(mVoteData.IsFocused() ? String.valueOf(mOptionPercent) + "%" : "");
            optionViewUp.mPercentText.setTextSize(mVoteData.IsFocusedIndex(i) ? 13 : 12);
            optionViewUp.mOptionName.setTextSize(mVoteData.IsFocusedIndex(i) ? 13 : 12);
            if(mVoteData.getQAAnswerReveal()) {
                optionViewUp.mVoteImg.setImageDrawable(mVoteData.getQAAnswerDrawable(i));
            } else {
                optionViewUp.mVoteImg.setImageResource(mVoteData.IsFocusedIndex(i) ? R.drawable.icon_choosed : R.drawable.icon_choose);
            }

            final View optionPercentLine = optionViewUp.mPercentLine;
            optionPercentLine.setBackgroundColor(getResources().getColor(mVoteData.getOptionColor(i)));

            final int mProgressTgtWidth = mVoteData.IsFocused() ? mOptionGp.getMeasuredWidth() * mOptionPercent / 100 : 0;
            final int mProgressCurWidth = optionPercentLine.getMeasuredWidth();

            mProgressAnimator = ValueAnimator.ofFloat(0, 1);
            mProgressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();

                    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) optionPercentLine.getLayoutParams();
                    params.width = (int) (mProgressCurWidth + (mProgressTgtWidth - mProgressCurWidth) * value);
                    optionPercentLine.setLayoutParams(params);
                }
            });
            mProgressAnimator.setDuration(200);
            mProgressAnimator.start();
        }

        mParticipantsText.setText(String.valueOf(mVoteData.getTotalCount()) + " 人参加");
    }

    @Override
    protected void startExpandAnim() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "startExpandAnim");

        mBAnimating = true;

        mOptionGp.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        mOptionGpHeight = mOptionGp.getMeasuredHeight();
        final float oriHeight = mRoot.getHeight();
        final float targetHeight = mTitleText.getMeasuredHeight() + mParticipantsText.getMeasuredHeight() + mOptionGpHeight + mTasteStyleHeight;

        final ValueAnimator anim = ValueAnimator.ofFloat(0.0f, 1.0f);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animValue = (float) animation.getAnimatedValue();

                LayoutParams params = (LayoutParams) mRoot.getLayoutParams();
                params.height = mAnimHeight = (int) (oriHeight + (targetHeight - oriHeight) * animValue);

                mRoot.setLayoutParams(params);
                mFoldText.setAlpha(animValue);
                mOptionGp.setAlpha(animValue);
            }
        });

        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mBAnimating = false;
                mBExpanded = true;

                // load preset data if not fold default
                if(!mBPreloadDataLoaded)
                    loadPresetData();
            }
        });

        anim.setDuration(400);
        anim.setTarget(mRoot);
        anim.start();

        Utils.Log(Utils.LogType.DEBUG, TAG, "startExpandAnim done");
    }

    @Override
    protected void startCollapseAnim() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "startCollapseAnim");

        mBAnimating = true;

        final float oriHeight = mRoot.getHeight();
        final float targHeight = mTitleText.getMeasuredHeight() + mParticipantsText.getMeasuredHeight() + mDivisionViewHeight + mTasteStyleHeight;

        final ValueAnimator anim = ValueAnimator.ofFloat(0.0f, 1.0f);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animValue = (float) animation.getAnimatedValue();

                LayoutParams params = (LayoutParams) mRoot.getLayoutParams();
                params.height = mAnimHeight = (int) (oriHeight - (oriHeight - targHeight) * animValue);

                mRoot.setLayoutParams(params);
                mFoldText.setAlpha(animValue);
                mRoot.requestLayout();

                mOptionGp.setAlpha(1 - animValue);
            }
        });

        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mBAnimating = false;
                mBExpanded = false;
                mOptionGp.setVisibility(View.GONE);
                mDivisionView.setVisibility(View.VISIBLE);
            }
        });

        anim.setDuration(400);
        anim.setTarget(mRoot);
        anim.start();

        Utils.Log(Utils.LogType.DEBUG, TAG, "startCollapseAnim done");
    }

    @Override
    public String getType() {
        return TYPE_QA;
    }

    @Override
    public void doNext() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "doNext");

        if(iSender != null)
            iSender.startSync(mData.rid, false);
    }

    private int mCountdown = -1;
    @Override
    public void syncData(OptionResultModel response) {
        Utils.Log(TAG, "[syncData]");

        if(mVoteData.getQAAnswerReveal()) {
            return;
        }

        if(mCountdown == 0) {
            Utils.Log(TAG, "[syncData] mCountdown = 0");
            mVoteData.setQAAnswerReveal(true);
            updateView();
        } else if (mCountdown > 0) {
            Utils.Log(TAG, "[syncData] mCountdown = " + mCountdown);
            mParticipantsText.setText(String.valueOf(mCountdown) + "秒后揭晓答案");
            mCountdown--;
        }
    }

    @Override
    public boolean IsPreviewDataSynced() {
        return true;
    }

    @Override
    public void syncPreviewData(ReportResultModel result) {
    }

    @Override
    protected void loadPresetData() {
        if(!mVoteData.getPresetDataLoad() && mPreselectedIndex >= 0) {
            Utils.Log(TAG, "[loadPresetData] mPreselectedIndex = " + mPreselectedIndex);
            mVoteData.restorePreselectedIndex(mPreselectedIndex);
            updateView();
            mVoteData.setPresetDataLoad(true);
        }
    }
}
